package qq2564874169.tuaotuao.fx.orm.jdbc.impl;



import qq2564874169.tuaotuao.fx.orm.CursorReader;
import qq2564874169.tuaotuao.fx.orm.SqlParam;
import qq2564874169.tuaotuao.fx.orm.jdbc.AbstractJDBCSql;
import qq2564874169.tuaotuao.fx.orm.mybatis.SqlPager;
import qq2564874169.tuaotuao.fx.orm.query.PageSet;
import qq2564874169.tuaotuao.fx.utils.ExUtil;
import qq2564874169.tuaotuao.fx.utils.StringUtil;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MysqlSql extends AbstractJDBCSql {
    public MysqlSql(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    protected PreparedStatement createStatement(Connection connection, SqlParam param, int fetchSize) {
        try {
            if (param.isProc) {
                String ps = StringUtil.repeat("?", param.args.size(), ",");
                param.command = String.format("{call %s(%s)}", param.command, ps);
            }
            PreparedStatement statement = connection.prepareStatement(param.command);
            if (param.timeout != null) {
                statement.setQueryTimeout(param.timeout);
            }
            if (fetchSize != 0) {
                statement.setFetchSize(fetchSize);
            }
            if (!param.args.isEmpty()) {
                List<Object> list = new ArrayList<>(param.args.values());
                for (int i = 0; i < list.size(); i++) {
                    statement.setObject(i + 1, list.get(i));
                }
            }
            return statement;
        } catch (SQLException e) {
            throw ExUtil.toRuntime(e);
        }
    }

    @Override
    protected <T> CursorReader<T> onCursor(Class<T> clazz, SqlParam param, int fetchSize, boolean independent) {
        return super.onCursor(clazz, param, Integer.MIN_VALUE, independent);
    }

    @Override
    protected SqlPager getPager(PageSet pageSet) {
        return new SqlPager() {
            private PageSet ps = pageSet;

            @Override
            public String countSql(String sql) {
                return "select count(1) c from(" + sql + ") t";
            }

            @Override
            public String dataSql(String sql) {
                int start = (ps.pageIndex - 1) * ps.pageSize;
                return sql + " limit " + start + "," + ps.pageSize;
            }
        };
    }

    @Override
    public String escapeField(String field) {
        return "`" + field + "`";
    }
}
